package com.yifeng.repo.base.utils;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by daibing on 2018/8/9.
 */
public class MapHelper {

    private static final String DEF_CHARSET = "utf-8";

    public static String map2JSON(Map<String, String> map, boolean quota) {
        if (map == null) {
            return null;
        }
        if (map.size() == 0) {
            return "{}";
        }
        StringBuilder sb = new StringBuilder("{");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                if (quota) {
                    sb.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\"").append(",");
                } else {
                    sb.append("\"").append(entry.getKey()).append("\":").append(entry.getValue()).append(",");
                }
            }
        }
        if (sb.length() > 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        sb.append("}");
        return sb.toString();
    }

    public static String map2String(Map<String, String> paramsMap, boolean encode) {
        try {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                sb.append(entry.getKey())
                        .append("=")
                        .append(encode ? URLEncoder.encode(entry.getValue(), DEF_CHARSET) : entry.getValue())
                        .append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.fillInStackTrace();
            return null;
        }
    }

    public static Map<String, String> model2Map(Object model) {
        Map<String, String> map = new HashMap<>();
        Field[] fields = model.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                if (field.get(model) == null) {
                    continue;
                }
                String key = field.getName();
                if ("__PARANAMER_DATA".equals(key)) {
                    continue;
                }
                String value = field.get(model).toString();
                map.put(key, value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("model2Map get failed: " + field.toString());
            }
        }
        return map;
    }

}
